package com.kantboot.functional.im.server;

import com.kantboot.functional.im.config.WebsocketConfig;
import com.kantboot.functional.im.service.IFunctionalImWebSocketService;
import jakarta.annotation.Resource;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * SocketTestServer
 */
@Slf4j
@Component
@ServerEndpoint(value="/ws/{cid}",configurator =  WebsocketConfig.CustomConfigurator.class)
public class WebsocketServer {

    @Resource
    private IFunctionalImWebSocketService service;


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("cid") String cid,Session session) {
        service.openWebSocket(cid,session);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session,@PathParam("cid") String cid) {
        service.closeWebSocket(cid);
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session,@PathParam("cid") String cid) {
        log.info("服务端收到客户端[{}]的消息:{},cid:{}", session.getId(), message,cid);
        service.onWebsocketMessage(cid,message);
    }

    @OnError
    public void onError(Session session, Throwable error,@PathParam("cid") String cid) {
        log.error("发生错误:{}", error.getMessage());
    }

    /**
     * 发送消息
     */
    public void sendMessageByCid(String cid, String message) {
        Session session = service.getSession(cid);
        try {
            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("发送消息出错:{}", e.getMessage());
        }
    }

    /**
     * 根据session发送消息
     */
    public void sendMessageBySession(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("发送消息出错:{}", e.getMessage());
        }
    }
}
